/*
 * @Author: hcluo
 * @Date: 2020-04-26 14:48:22
 * @LastEditors: hcluo
 * @LastEditTime: 2020-06-12 20:27:10
 * @Description: 政府项目
 */

import { getQueryString } from './utils/util.js';

// url 配置
const config = {
    fetchData: {
        url: '/govwebapi/gov/web/api/integration/dataset/datainfo',
    },
    // 获取页面配置
    fetchPage: {
        url: '/govwebapi/gov/web/api/user/stdpage/config',
    },
};

const session = getQueryString('wind.sessionid') || 'ff42543bf81b414dbc1d6ca095f7e499';
let right = getQueryString('right');
let host = (() => {
    // 添加sessionStorage
    let host = getQueryString('host');
    return !!host ? host : 'http://180.96.8.44';
})();

export const requests = {};
// let requests = {}

for (let [k, v] of Object.entries(config)) {
    let { url, method } = v;
    let opt = {
        method: method || 'GET',
        headers: {
            'Content-Type': 'application/json',
        },
    };

    // 第三方鉴权码
    if (!!right) opt.headers.right = right;

    if (!window.external || !window.external.ClientFunc) {
        opt.headers['wind.sessionid'] = session;
    }

    requests[k] = (code, business) => {
        let params = {},
            body = {};
        // url 中携带module code 方便调试的时候查找
        let newUrl = url + '?code=' + code;

        if (business.params !== undefined) params.business = business.params;
        if (business.body !== undefined) body.business = business.body;

        // url 参数拼装
        params['wind.sessionid'] = session; // URL中不需要 session 时删除该行代码

        for (let [key, value] of Object.entries(params)) if (!!value) newUrl += `&${key}=${JSON.stringify(value)}`; // 若value没有值，则不添加该字段

        // 若有body，则添加
        if (body.business) {
            opt.body = JSON.stringify(body);
        }

        return fetch(host + newUrl, opt)
            .then(response => {
                if (!response.ok) {
                    return Promise.reject(response.status);
                }
                return response.json();
            })
            .then(res => {
                if (res.resultCode === '200') {
                    return Promise.resolve(res.resultData);
                } else if (res.resultCode === '403') {
                    window.location.href = './403.html';
                } else {
                    console.error('服务端错误：', config.host + url, res);
                    return Promise.reject(res.resultMessage);
                }
            });
    };
}

console.log('%c 🍦 requests: ', 'font-size:20px;background-color: #B03734;color:#fff;', requests);
